package com.can.core.shiro;

import com.alibaba.fastjson.JSON;
import com.can.common.constant.JsonResultEnum;
import com.can.entityDTO.JsonResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * @Desription 登录拦截器，未登录返回到登录页面，ajax请求返回json数据
 * @Author can
 * @Date 2018/10/10
 * @Version 1.0
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {
                return this.executeLogin(request, response);
            } else {
                return true;
            }
        } else {
       /*     String header = ((HttpServletRequest) request).getHeader("Content-Type");
            if (header != null && header.equals("application/x-www-form-urlencoded")) {
                //这句话的意思，是让浏览器用utf8来解析返回的数据
                response.setContentType("text/html;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                PrintWriter out = response.getWriter();
                JsonResult jsonResult = new JsonResult(JsonResultEnum.NO_LOGIN_ERROR);
                out.print(JSON.toJSONString(jsonResult));
                out.flush();
                out.close();
            } else {
                this.saveRequestAndRedirectToLogin(request, response);
            }*/
            //这句话的意思，是让浏览器用utf8来解析返回的数据
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            JsonResult jsonResult = new JsonResult(JsonResultEnum.NO_LOGIN_ERROR);
            out.print(JSON.toJSONString(jsonResult));
            out.flush();
            out.close();
            return false;
        }
    }
}